package service.impl;

import entity.Book;
import entity.Borrow;
import repository.BookRepository;
import repository.BorrowRepository;
import repository.impl.BookRepositoryImpl;
import repository.impl.BorrowRepositoryImlp;
import service.BookService;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class BookServiceImpl implements BookService {
    /*public BookServiceImpl() {
    }*/
    private final int LIMIT=6;
    public BookRepository bookRepository=new BookRepositoryImpl();
    public BorrowRepository borrowRepository=new BorrowRepositoryImlp();

    @Override
    public List<Book> findAll(int page) throws SQLException {
        int index=(page-1)*LIMIT;
        return bookRepository.findAll(index,LIMIT);
    }

    @Override
    public int getPages() throws SQLException {
        int count=bookRepository.count();
        int page=0;
        if(count % LIMIT ==0){
            page=count/LIMIT;
        }
        else {
            page=count/LIMIT+1;
        }
        return page;
    }

    @Override
    public int getBorrowPages(Integer readerId) throws SQLException {
        int count=borrowRepository.count(readerId);
        int page=0;
        if(count % LIMIT ==0){
            page=count/LIMIT;
        }
        else {
            page=count/LIMIT+1;
        }
        return page;
    }

    @Override
    public void addBorrow(Integer bookid, Integer readerid) throws SQLException {
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String borrowTime=simpleDateFormat.format(date);
        Calendar calendar=Calendar.getInstance();
        int dates=calendar.get(Calendar.DAY_OF_YEAR)+14;
        calendar.set(Calendar.DAY_OF_YEAR,dates);
        Date date2=calendar.getTime();
        String returnTime=simpleDateFormat.format(date2);
        borrowRepository.insert(bookid,readerid,borrowTime,returnTime,null,0);
    }

    @Override
    public List<Borrow> findAllBorrowByReaderId(Integer id,Integer page) throws SQLException {
        int index=(page-1)*LIMIT;
        return borrowRepository.findAllByReaderId(id,index,LIMIT);
    }

    @Override
    public List<Borrow> findAllBorrowByState(Integer state,Integer page) throws SQLException {   int index=(page-1)*LIMIT;
        return borrowRepository.findAllByState(state,index,LIMIT);
    }

    @Override
    public int getBorrowPagesByState(Integer state) throws SQLException {
        int count=borrowRepository.countByState(state);
        int page=0;
        if(count % LIMIT ==0){
            page=count/LIMIT;
        }
        else {
            page=count/LIMIT+1;
        }
        return page;
    }

    @Override
    public void handleBorrow(Integer borrowId, Integer state, Integer adminId) throws SQLException {
    borrowRepository.handle(borrowId,state,adminId);
    }
}
